<template>
  <div class="m-slide">
    <ul class="m-slide-image" :style="{width:data.length*100+'%',marginLeft:-mActiveIndex*100+'%'}">
      <li 
      v-for="(item,index) in data"
      :key="item.id">
        <slot :item="item" :index="index">
          {{index}}-{{item.title}}<!--默认布局-->
        </slot>
      </li>
    </ul>
    <ul class="m-slide-dot">
      <li 
      @click="handleClick($event,index)"
      v-for="(item,index) in data"
      :key="item.id" :class="mActiveIndex==index?'m-slide-dot-actived':''">{{index+1}}</li>
    </ul>
  </div>
</template>

<script>
export default {
  name: "Slide",
  props: {
    data: { // 轮播图数据
      type: Array,
      default() {
        return []
      }
    },
    activeIndex: { // 当前索引值
      type: Number,
      default: 0
    },
    interval: {// 周期s
      type: Number,
      default: 2000
    }
  },
  data() {
    return {
      timer: undefined, // 定义器
      mActiveIndex: this.activeIndex
    }
  },
  mounted() { // 挂载到dom时执行定义器
    this.timer = setInterval(() => {
      // 定时器循环自增索引
      if(this.mActiveIndex==this.data.length-1) {
        this.mActiveIndex = 0
      } else {
        this.mActiveIndex = this.mActiveIndex+1
      }
    }, this.interval);
  },
  beforeUnmount() {
    if(this.timer) { // 销毁时清除定时器
      clearInterval(this.timer)
    }
  },
  methods: {
    // 处理圆点点击事件
    handleClick(e, index) {
      this.mActiveIndex = index
    }
  }
}
</script>

<style scoped>
ul,li{
      margin: 0;
      padding: 0;
      list-style: none;
    }
    .m-slide{
      width: 100%;
      height: 300px;
      border: 1px solid red;
      overflow: hidden;
      position: relative;
    }
    .m-slide-image{
      display: flex;
      width: 400%;
      height: 300px;
      /*margin-left从A值变到B值所需要的时长为0.8s*/
      transition: margin-left 0.8s;
      margin-left: 0%;
    }
    .m-slide-image li{
      flex: 1;
    }
    .m-slide-dot{
      height: 44px;
      bottom: 10px;
      right: 14px;
      position: absolute;
      display: flex;
    }
    .m-slide-dot li{
      width: 44px;
      height: 44px;
      border-radius: 22px;
      margin-left: 6px;
      display: flex;
      justify-content: center;
      align-items: center;
      background: #cccccc;
      cursor: pointer;
    }
    
    li.m-slide-dot-actived{
      background: #ffe121;
    }
    
</style>
